﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Devonline.Identity.Admin.Controllers;

/// <summary>
/// 基础数据管理
/// </summary>    
[Route("api/[controller]")]
[ApiController]
[SecurityHeaders]
[Authorize(Roles = GROUP_MAINTAINERS)]
public class ParametersController(
    ILogger<ParametersController> logger,
    IDataService<Parameter> dataService) :
    ODataModelServiceController<Parameter, ParameterViewModel>(logger, dataService)
{
    /// <summary>
    /// 初始化基础数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("init")]
    public async Task<IActionResult> InitParameter()
    {
        var parameter = await _dataService.GetQueryable().FirstOrDefaultAsync(x => x.Key == "root");
        if (parameter != null)
        {
            return Ok("已经初始化过了!");
        }

        parameter = new Parameter
        {
            Id = "0",
            Index = 0,
            Key = "root",
            Value = "Root",
            Text = "基础数据根节点"
        };
        parameter.Create();
        var list = new List<Parameter> { parameter };
        var types = typeof(AppSetting).Assembly.GetTypes().Where(x => x.IsEnum);
        if (types.Any())
        {
            var index = 101;
            var extensionType = typeof(AspNetCoreExtensions);
            var toLowerTypes = new string[] { nameof(DatabaseType), nameof(EncryptionAlgorithm), nameof(HashAlgorithm), nameof(SymmetricAlgorithm), nameof(Currency) };
            var boolTypes = new string[] { nameof(YesOrNo), nameof(HaveOrNot), nameof(AgreeOrNot) };
            foreach (var type in types.Where(x => !boolTypes.Contains(x.Name)))
            {
                var parameters = extensionType.InvokeGenericMethod<List<Parameter>>(nameof(AspNetCoreExtensions.GetParametersFromEnum), index++, [toLowerTypes.Contains(type.Name)], type);
                if (parameters is not null && parameters.Count != 0)
                {
                    list.AddRange(parameters);
                }
            }

            index = 201;
            foreach (var type in types.Where(x => boolTypes.Contains(x.Name)))
            {
                var parameters = extensionType.InvokeGenericMethod<List<Parameter>>(nameof(AspNetCoreExtensions.GetBoolParametersFromEnum), index++, [toLowerTypes.Contains(type.Name)], type);
                if (parameters is not null && parameters.Count != 0)
                {
                    list.AddRange(parameters);
                }
            }
        }

        _dataService.SetAutoSaveChanges(false);
        foreach (var item in list)
        {
            await _dataService.AddAsync(item);
        }

        await _dataService.SaveChangesAsync();
        return Ok("初始化完成!");
    }
}